package com.zzmcc.common;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.zzmcc.sys.model.Authorize;
import com.zzmcc.sys.model.Userinfo;
import util.StringUtil;

/**
 * Created by zhuangyw on 15/1/28.
 */
public class AuthorizeInterceptor implements Interceptor {
    @Override
    public void intercept(ActionInvocation ai) {

        String actionKey = ai.getActionKey();
        int roleid=-1;
        Userinfo loginUser =ai.getController().getSessionAttr("loginUser");
        if (null!=loginUser) {
            roleid = loginUser.get("roleid");
            actionKey = StringUtil.replaceAll(actionKey, "/", "_");
            System.out.println(actionKey);
            String sql="SELECT * from sys_role_permission a\n" +
                    "LEFT JOIN sys_permission b\n" +
                    "on a.pid=b.id\n" +
                    "where roleid=? and name=?";
            Record record= Db.findFirst( sql,roleid,actionKey);
            /*
            Authorize authorize = Authorize.dao.findFirst("select * from sys_authorize where groupid=? and actionKey=?",
                    roleid,actionKey);
                    */
            if ((roleid == 0)||(null != record)) {
                ai.invoke();
            } else {
                ai.getController().renderError(403);
            }
        }else {
            //登录超时
            ai.getController().renderError(401);
        }


    }
}
